<?php
/**
 * Created by PhpStorm.
 * User: zhangxilu
 * Date: 2017/12/20
 * Time: 下午9:40
 */

namespace common\logic;


use common\models\BaseHouseMarkModel;
use common\models\BaseHouseTypeModel;
use common\models\BaseRentingPriceModel;
use common\models\BaseUnitPriceModel;
use common\models\RentingModel;
use common\models\BaseRegionModel;
use common\models\RentingMarkModel;
use common\models\RentingBrandModel;
use common\logic\RentingBrandLogic;
use yii\db\ActiveQuery;
use yii\helpers\ArrayHelper;

class RentingLogic extends Logic
{

    /**
     * @return ActiveQuery
     */
    protected function _getActiveQuery()
    {
        return RentingModel::find();
    }

    public function getAll($ids){
        return $this->_all(['id'=>$ids]);
    }

    public function getHouseDetail($id,$uid='0')
    {
        $house = $this->getById($id);
        $has_attention=0;

        if (empty($house)) {
            return false;
        }

        $images = RentingImageLogic::instance()->getAll($id);
        $newImages = [];
        if (!empty($images)) {
            foreach ($images as $image) {
                $newImages[] = $image->img_path;
            }
        }

        if (!empty($house->decoration_id)) {
            $decoration = DecorationTypeLogic::instance()->get($house->decoration_id);
        }
        if (!empty($house->region_id)) {
            $region = RegionLogic::instance()->getById($house->region_id);
            $parent_region = RegionLogic::instance()->getParent($region->id);

        }

        $houseTypeImage = RentingTypeImageLogic::instance()->getAll($house->id);

        $newHouseTypeImage = [];
        if (!empty($houseTypeImage)) {
            foreach ($houseTypeImage as $item) {
                $item = $item->toArray(['img_path', 'name', 'area', 'price', 'house_type']);

                $newHouseTypeImage[] = $item;
            }
        }

        $result = $house->toArray();

        $result['decoration'] = empty($decoration) ? '' : $decoration->decoration_type;
        $result['region'] = empty($region) ? '' :  $region->region_name;
        $result['parent_region'] = empty($parent_region) ? '' :  $parent_region->region_name;
        $result['category'] = empty($category) ? '' : $category->category;
        $result['images'] = $newImages;
        $result['houseTypeImage'] = $newHouseTypeImage;
        $result['marks']=$this->getHouseMarks($result['id']);

        $result['house_unit_price'] = sprintf('%s-%s',$result['house_unit_price1'],$result['house_unit_price2']);
        unset($result['house_unit_price1'],$result['house_unit_price2']);




        return ['house' => $result];
    }

    public function getAdv()
    {
        /**
         * @var $banners RentingModel[]
         */
        $banners = $this->getQuery(['is_banner_home' => 1], [], ['id','banner'], ['id' => SORT_DESC])->andWhere("banner>''")->limit(6)->all();
        $newBanners = [];
        foreach ($banners as $banner) {
            $newBanners[] = ["id"=>$banner->id,"banner"=>$banner->banner];
        }
        /**
         * @var $adv RentingModel
         */
        $adv = $this->getQuery(['is_adv' => 1], [], ['id','adv'], ['id' => SORT_DESC])->andWhere("adv>''")->limit(1)->one();
        $newAdv = '';
        if (!empty($adv)) {
            $newAdv =["id"=>$adv->id,"adv"=>$adv->adv];
        }

        return ['banners' => $newBanners, 'adv' => $newAdv];
    }

    public function getListBanner()
    {
        /**
         * @var $banners RentingModel[]
         */
        $banners = $this->getQuery(['is_banner' => 1], [], ['id','banner'], ['id' => SORT_DESC])->andWhere("banner>''")->limit(6)->all();
        $newBanners = [];
        foreach ($banners as $banner) {
            $newBanners[] = ["id"=>$banner->id,"banner"=>$banner->banner];
        }

        return ['banners' => $newBanners];
    }



    /**
     * @param $id
     *
     * @return array|null|RentingModel
     */
    protected function getById($id)
    {
        return $this->_get(['id' => $id]);
    }

    /**
     * 推荐楼盘
     *
     * @return array
     */
    public function getRecommend()
    {

        //上海楼盘
        $query = $this->_getActiveQuery();
        $query = $query->select(['a.id','a.region_id', 'house_name','c.region_name as parent_region','a.address','b.region_name', 'house_unit_price1', 'house_unit_price2'])->alias('a')->leftJoin('ph_base_region b','a.region_id=b.id')->leftJoin('ph_base_region c','b.parent=c.id')->limit(5)->orderBy(['is_recommend'=>SORT_DESC,'recommend_sort' => SORT_DESC,'a.id' => SORT_DESC]);
        $data_sh = $query->asArray()->all();

        if (!empty($data_sh)) {
            $hourseIds = ArrayHelper::getColumn($data_sh, 'id');
            $images = RentingImageLogic::instance()->getFirstImage($hourseIds);

            foreach ($data_sh as $k => $v) {
                $v['marks']=$this->getHouseMarks($v['id']);
                $v['img_path'] = empty($images[$v['id']]) ? '' : $images[$v['id']];
                $v['house_unit_price'] = sprintf('%s-%s',$v['house_unit_price1'],$v['house_unit_price2']);
                unset($v['house_unit_price1'],$v['house_unit_price2']);
                $data_sh[$k] = $v;
            }

        }




        return ['list_sh' => $data_sh];
    }

    /**
     * 同区域的楼盘推荐
     *
     * @return array
     */
    public function getSameRegionHouse($region_id)
    {

        $query = $this->_getActiveQuery();
        $query = $query->select(['a.id','a.region_id', 'house_name','c.region_name as parent_region','a.address','b.region_name', 'house_unit_price1', 'house_unit_price2'])->alias('a')->leftJoin('ph_base_region b','a.region_id=b.id')->leftJoin('ph_base_region c','b.parent=c.id')->where(['a.region_id'=>$region_id])->limit(5)->orderBy(['a.id' => SORT_DESC]);
        $data = $query->asArray()->all();

        if (!empty($data)) {
            $hourseIds = ArrayHelper::getColumn($data, 'id');
            $images = RentingImageLogic::instance()->getFirstImage($hourseIds);

            foreach ($data as $k => $v) {
                $v['marks']=$this->getHouseMarks($v['id']);
                $v['img_path'] = empty($images[$v['id']]) ? '' : $images[$v['id']];
                $v['house_unit_price'] = sprintf('%s-%s',$v['house_unit_price1'],$v['house_unit_price2']);
                unset($v['house_unit_price1'],$v['house_unit_price2']);
                $data[$k] = $v;
            }

        }

        return ['list' => $data];
    }

    /**
     * 分页
     *
     * @param        $page
     * @param int    $pageSize
     * @param array  $search
     *
     * @return array
     */
    public function getByPage($page, $pageSize = 20, $search = [])
    {
        $nextPage = 0;
        $offset = ($page - 1) * $pageSize;

        $query = $this->_getActiveQuery();
		
        $query = $query->select(['a.id','a.region_id', 'house_name','c.region_name as parent_region','a.address','b.region_name', 'house_unit_price1', 'house_unit_price2'])
            ->alias('a')
            ->leftJoin('ph_base_region b','a.region_id=b.id')
            ->leftJoin('ph_base_region c','b.parent=c.id')
            ->limit($pageSize + 1)->offset($offset);
		
        if (!empty($search['type']) && intval($search['type'])==1) {//按价格从低到高
            $query->orderBy(['a.house_unit_price1'=>SORT_ASC,'a.is_recommend'=>SORT_DESC,'a.recommend_sort' => SORT_DESC]);			
        }
        else if (!empty($search['type']) && intval($search['type'])==2) {//按价格从高到低
            $query->orderBy(['a.house_unit_price1'=>SORT_DESC,'a.is_recommend'=>SORT_DESC,'a.recommend_sort' => SORT_DESC]);
        }
        else{
            $query->orderBy(['a.is_recommend'=>SORT_DESC,'a.recommend_sort' => SORT_DESC,'a.id' => SORT_DESC]);
        }

        if (!empty($search['region'])) {
            if($search['region_type']=='1'){
                $query->andWhere(['region_id' => $search['region']]);
            }
            else{
                $rr=BaseRegionModel::find()->select(['id'])->where(['parent'=>$search['region']])->asArray()->column();

                $query->andWhere(['in','region_id',$rr]);
            }
        }

        if (!empty($search['price'])) {
            $unitPrice = BaseRentingPriceModel::findOne($search['price']);
            if (!empty($unitPrice)) {
                if (!empty($unitPrice->min_price)) {
                    $query->andWhere(['or',['and',['<=', 'house_unit_price1', $unitPrice->min_price],['>', 'house_unit_price2', $unitPrice->min_price]],['and',['<', 'house_unit_price1', $unitPrice->max_price],['>=', 'house_unit_price2', $unitPrice->max_price]],['and',['<', 'house_unit_price2', $unitPrice->max_price],['>=', 'house_unit_price2', $unitPrice->min_price]]]);
					
                }
            }
        }

        if (!empty($search['name'])) {
            $query->andFilterWhere(['like', 'house_name', $search['name']])
                ->orFilterWhere(['like', 'address', $search['name']]);
				
        }



        $data = $query->asArray()->all();
        if (count($data) > $pageSize) {
            unset($data[$pageSize]);
            $nextPage = $page + 1;
        }

        if (!empty($data)) {
            $hourseIds = ArrayHelper::getColumn($data, 'id');
            $images = RentingImageLogic::instance()->getFirstImage($hourseIds);

            foreach ($data as $k => $v) {
                $v['marks']=$this->getHouseMarks($v['id']);
                $v['img_path'] = empty($images[$v['id']]) ? '' : $images[$v['id']];
                $v['house_unit_price'] = sprintf('%s-%s',$v['house_unit_price1'],$v['house_unit_price2']);
                unset($v['house_unit_price1'],$v['house_unit_price2']);
                $data[$k] = $v;
            }

        }

        return ['nextPage' => $nextPage, 'list' => $data];
    }
	
	public function getPcByPage($page, $pageSize = 20, $search = [])
    {
    	
		$brandArr = RentingBrandLogic::instance()->getPcBrand($page,$pageSize);
		$PageNum = RentingBrandLogic::instance()->getPcBrandNum();
		$brandDataArr = [];
		$brandid = 0;
		
		$nextPage = 0;
		if (count($brandArr) > $pageSize) {
            $nextPage = $page + 1;
        }
		

		$BackArr = [];
		
		foreach($brandArr as $key=>$value){
			$brandid = $value['id'];
	
	        $query = $this->_getActiveQuery();
	        $query = $query->select(['a.id','a.region_id', 'house_name','c.region_name as parent_region','a.address','b.region_name', 'house_unit_price1', 'house_unit_price2','a.brandid'])
	            ->alias('a')
	            ->leftJoin('ph_base_region b','a.region_id=b.id')
	            ->leftJoin('ph_base_region c','b.parent=c.id')
				->andWhere(['a.brandid' => $brandid])
	            ->limit(12);
            
           

	        if (!empty($search['type']) && intval($search['type'])==1) {//按价格从低到高
	            $query->orderBy(['a.house_unit_price1'=>SORT_ASC,'a.is_recommend'=>SORT_DESC,'a.recommend_sort' => SORT_DESC]);
	        }
	        else if (!empty($search['type']) && intval($search['type'])==2) {//按价格从高到低
	            $query->orderBy(['a.house_unit_price1'=>SORT_DESC,'a.is_recommend'=>SORT_DESC,'a.recommend_sort' => SORT_DESC]);
	        }
	        else{
	            $query->orderBy(['a.is_recommend'=>SORT_DESC,'a.recommend_sort' => SORT_DESC,'a.id' => SORT_DESC]);
	        }
            
	        if (!empty($search['region'])) {
	            if($search['region_type']=='1'){
	                $query->andWhere(['region_id' => $search['region']]);
	            }
	            else{
	                $rr=BaseRegionModel::find()->select(['id'])->where(['parent'=>$search['region']])->asArray()->column();
	
	                $query->andWhere(['in','region_id',$rr]);
	            }
	        }
            
            if (!empty($search['name'])) {
                $query->andFilterWhere(['like', 'house_name', $search['name']])
                    ->orFilterWhere(['like', 'address', $search['name']]);
            }
            
	        if (!empty($search['price'])) {
	            $unitPrice = BaseRentingPriceModel::findOne($search['price']);
	            if (!empty($unitPrice)) {
	                // if (!empty($unitPrice->min_price)) {
	                    // $query->andWhere(['or',['and',['<=', 'house_unit_price1', $unitPrice->min_price],['>', 'house_unit_price2', $unitPrice->min_price]],['and',['<', 'house_unit_price1', $unitPrice->max_price],['>=', 'house_unit_price2', $unitPrice->max_price]],['and',['<', 'house_unit_price2', $unitPrice->max_price],['>=', 'house_unit_price2', $unitPrice->min_price]]]);
                        $query->andWhere(['or',
                        ['and',['<=', 'house_unit_price1', $unitPrice->min_price],['>', 'house_unit_price2', $unitPrice->min_price]],
                        ['and',['<', 'house_unit_price1', $unitPrice->max_price],['>=', 'house_unit_price2', $unitPrice->max_price]],
                        ['and',['<', 'house_unit_price2', $unitPrice->max_price],['>=', 'house_unit_price2', $unitPrice->min_price]]]);

                        // $query->andWhere(['and',['>=', 'house_unit_price1', $unitPrice->min_price],['<=', 'house_unit_price2', $unitPrice->max_price]]);
                    
                    // }
	            }
	        }
	
	        
			
			$query->andWhere(['brandid' => $brandid]);
	        $data = $query->asArray()->all();
	        
	        if (!empty($data)) {
	            $hourseIds = ArrayHelper::getColumn($data, 'id');
	            $images = RentingImageLogic::instance()->getFirstImage($hourseIds);
	
	            foreach ($data as $k => $v) {
	                $v['marks']=$this->getHouseMarks($v['id']);
	                $v['img_path'] = empty($images[$v['id']]) ? '' : $images[$v['id']];
	                $v['house_unit_price'] = sprintf('%s-%s',$v['house_unit_price1'],$v['house_unit_price2']);
	                unset($v['house_unit_price1'],$v['house_unit_price2']);
	                $data[$k] = $v;
	            }
	
	        }
			
			$BackArr[$key] = ['brand'=>$value,'list'=>$data];
//			$brandArr[$key]['data'] =$data;			
		}

		
		

        return ['nextPage' => $nextPage,'pageNum'=>$PageNum, 'list' => $BackArr];
    }
	
    protected function getHouseMarks($house_id){
        $marks=BaseHouseMarkModel::find()->select("a.mark")->alias('a')->leftJoin('ph_renting_mark b','b.mark_id=a.id')->where(['b.house_id'=>$house_id])->limit(4)->all();
        return ArrayHelper::getColumn($marks, 'mark');
    }

    public function houseSave(RentingModel $model)
    {
        $this->saveFile($model, 'banner');
        $this->saveFile($model, 'adv');
        if (!empty($model->building_type) && is_array($model->building_type)) {
            $type = $model->building_type;
            $model->building_type = join(',', $type);
        }


        if ($model->is_adv == 1) {
            $this->updateAdv();
        }

        $rs = $model->save();
        if($rs){
            $this->saveMarks($model);
        }

//        $rlt=$this->transaction(function (){
//            return true;
//        });
        return $rs;
    }

    protected function saveMarks($model){
        $hid = $model->attributes['id'];
        $houseMarkModel=new RentingMarkModel();

        if (!empty($hid)&&!empty($model->house_mark) && is_array($model->house_mark)) {
            $marks = $model->house_mark;

            $houseMarkModel::deleteAll(['house_id'=>$hid]);

            foreach ($marks as $key => $value) {
                $houseMarkModel=new RentingMarkModel();
                $houseMarkModel->house_id=$hid;
                $houseMarkModel->mark_id=$value;
                $houseMarkModel->save();
            }
        }
    }


    /**
     * 保存上传文件banner、广告位
     *
     * @param \common\models\RentingModel $model
     * @param                           $key
     */
    protected function saveFile(RentingModel $model, $key)
    {
        if ($_FILES && !empty($_FILES['RentingModel']['name'][$key])) {
            $filePath = "/upload/renting/$key/";
            $fileName = $filePath . uniqid() . '.' . pathinfo($_FILES['RentingModel']['name'][$key], PATHINFO_EXTENSION);
            $filePath = \Yii::getAlias('@webroot') . $filePath;
            if (!file_exists($filePath)) {
                mkdir($filePath, 0777, true);
            }
            $savePath = \Yii::getAlias('@webroot') . $fileName;
            if (move_uploaded_file($_FILES['RentingModel']['tmp_name'][$key], $savePath)) {
                $model->$key = $fileName;
            }
        }
    }


    protected function updateAll($set, $where)
    {
        RentingModel::updateAll($set, $where);
    }

    public function updateAdv()
    {
        $this->updateAll(['is_adv' => 0], ['is_adv' => 1]);
    }
	
	public function getBrandNum($brandid){
		$brand = $this->getQuery(['brandid' => $brandid])->all();
        return count($brand);
	}

}